package fschmidt.util.mail;


public class SmtpServerPool implements SmtpServer {
	private SmtpServer[] servers;
	private volatile SmtpServer defaultServer;

	SmtpServerPool(SmtpServer... servers) {
		this.servers = servers;
		defaultServer = servers[0];
	}
	
	public void send(Mail mail, MailAddress... addresses) throws MailException {
		SmtpServer server = defaultServer;
		try {
			server.send(mail, addresses);
			return;
		} catch (MailParseException e) {
			throw e;
		} catch (MailAddressException e) {
			throw e;
		} catch (MailEncodingException e) {
			throw e;
		} catch (MailException e) {
			for (SmtpServer fallbackServer : servers) {
				if (fallbackServer == server) continue;
				try {
					fallbackServer.send(mail, addresses);
					defaultServer = fallbackServer;
					return;
				} catch (MailException e2) {
					e = e2;
				}
			}
			throw new MailException("all smtp servers failed", e);
		}
	}
	
	public void sendFrom(final Mail mail, final String smtpFrom) throws MailException {
		SmtpServer server = defaultServer;
		try {
			server.sendFrom(mail, smtpFrom);
			return;
		} catch (MailParseException e) {
			throw e;
		} catch (MailAddressException e) {
			throw e;
		} catch (MailEncodingException e) {
			throw e;
		} catch (MailException e) {
			for (SmtpServer fallbackServer : servers) {
				if (fallbackServer == server) continue;
				try {
					fallbackServer.sendFrom(mail, smtpFrom);
					defaultServer = fallbackServer;
					return;
				} catch (MailException e2) {
					e = e2;
				}
			}
			throw new MailException("all smtp servers failed", e);
		}
	}
	
	public void useSsl() {
		for (SmtpServer server : servers) {
			server.useSsl();
		}
	}
	
	public void useStartTls() {
		for (SmtpServer server : servers) {
			server.useStartTls();
		}
	}
	
	public void setPort(int port) {
		for (SmtpServer server : servers) {
			server.setPort(port);
		}
	}
	
	public void setDebug(boolean b) {
		for (SmtpServer server : servers) {
			server.setDebug(b);
		}
	}
	
	public String getUserName() {
		return defaultServer.getUserName();
	}
}
